/****************************************************************

kernel/hdd.c
Hard disk drive driver for AWOS

Copyright (c) 2006 Andrew Wilcox. All rights reserved.

Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the following
conditions are met:

1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.

3. The end-user documentation included with the redistribution,
if any, must include the following acknowledgment:

"This product includes software developed by Andrew Wilcox for
AWOS. (http://code.google.com/p/awos)."

Alternately, this acknowledgment may appear in the software
itself, if and wherever such third-party acknowledgments normally
appear.

4. The names "AWOS" and "Andrew Wilcox" must not be used to
endorse or promote products derived from this software without
prior written permission. For written permission, please contact
Andrew.R.Wilcox@Gmail.com.

5. Products derived from this software may not be called "AWOS"
 nor may "AWOS" appear in their name, without prior written
 permission of Andrew Wilcox.

THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL ANDREW WILCOX BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.

****************************************************************/

#include <kernel.h>
#include <driver/hdd.h>
#include <asm.h>
#include <unistd.h>
#include <string.h>

BOOL KiHardDiskDetect(int base, int drive, struct KiAtapiDisk *ad);
void HdIrqHandler(struct regs *r);

static int status;

/****************************************************************
KsHardDisk() - initializes all hard disks
Input:	nothing
Output:	struct KiDiskLayout
****************************************************************/
struct KiDiskLayout *KsHardDisk()
{
	struct KiDiskLayout *layout;
	
	layout = kmalloc(sizeof(struct KiDiskLayout));
	if(layout == NULL) return FALSE;
	
	KiIrqInstall(0x0E, HdIrqHandler);
	KiIrqInstall(0x0F, HdIrqHandler);
	
	layout->pri.master.exists = KiHardDiskDetect(PORT_ATAPI_PRIBASE, 0, &(layout->pri.master));
	layout->pri.slave.exists  = KiHardDiskDetect(PORT_ATAPI_PRIBASE, 1, &(layout->pri.slave));
	layout->sec.master.exists = KiHardDiskDetect(PORT_ATAPI_SECBASE, 0, &(layout->sec.master));
	layout->sec.slave.exists  = KiHardDiskDetect(PORT_ATAPI_SECBASE, 1, &(layout->sec.slave));
	
	return layout;
}

BOOL KiHardDiskDetect(int base, int drive, struct KiAtapiDisk *ad)
{
	char *mbr;
	char *buffer;
	
	buffer = kmalloc(512);
	if(buffer == NULL) return FALSE;
	
	memset((unsigned char *)buffer, 0, sizeof(struct KiAtapiIdent));
	
	outportb(base + PORT_ATAPI_DRIVE, (drive<<4) + 0xA0);
	outportb(base + PORT_ATAPI_COMMAND, 0xEC);	/* EIDE ident */
	while((inportb(base + 0x306) & 0x08) == 0) ;	/* wait for drive to become ready */
	
	inportw_string(base + PORT_ATAPI_DATA, 256, (unsigned short *)buffer);
	swab(buffer, &(ad->ident), sizeof(struct KiAtapiIdent));
	kfree(buffer);
	
	if(!(ad->ident.log_cyl & 0x40) || ad->ident.config == -1)
	{
		dprintf("hd: no disk found on ide%i:%i: got %04X\n", (base == 0x1F0 ? 0 : 1), drive, ad->ident.config);
		return FALSE;
	}
	
	dprintf("hd: detected '%40s' at ide%i:%i\n", ad->ident.model, (base == 0x1F0 ? 0 : 1), drive);
	
	mbr = kmalloc(512);
	if(!HdReadSector(drive, (base == 0x1F0 ? 0 : 1), 1, 0, mbr))
		dprintf("hd: critical error: could not read MBR!\n");
	else
		dprintf("last two bytes of MBR: %02X %02X\n", mbr[510], mbr[511]);
	
	kfree(mbr);
	
	return TRUE;
}

/*! \fn int HdReadSector(char drive, BOOL pri, size_t sec_count, long lba_address, char *data)
 * \brief reads in >=1 sectors from a hard disk
 * \param drive	drive # (valid 0-1)
 * \param pri if TRUE, read from primary IDE controller, if FALSE, read from secondary IDE controller.
 * \param sec_count number of sectors to read
 * \param lba_address LBA sector number
 * \param data pointer to buffer to put data in
 * \return error code as defined in driver/hdd.h
 */
int HdReadSector(char drive, BOOL pri, size_t sec_count, long lba_address, char *data)
{
	char *temp;
	int base;
	
	if(pri == TRUE)
		base = PORT_ATAPI_PRIBASE;
	else
		base = PORT_ATAPI_SECBASE;
	
	if(drive > 1)
		return HDE_INVALIDDRIVE;
	
	/* according to the ATA-6 standard, you can't write to the registers
	   unless the BSY bit is clear.  so don't outportb until then */
	while(inportb(base + PORT_ATAPI_STATUS) & HDS_BSY);
	
	/* BSY clear, so set them registers */
	outportb(base + PORT_ATAPI_SECCOUNT, sec_count);
	outportb(base + PORT_ATAPI_LBALOW, (unsigned char)lba_address);
	outportb(base + PORT_ATAPI_LBAMID, (unsigned char)lba_address>>8);
	outportb(base + PORT_ATAPI_LBAHIGH,(unsigned char)lba_address>>16);
	outportb(base + PORT_ATAPI_DRIVE, (0xE0 | (drive << 4) | ((lba_address >> 24) & 0x0F)));
	
	/* according to the ATA-3 standard, you should (don't have to but SHOULD)
	   wait until the DRDY bit is set before writing a command, even if the
	   BSY bit is clear */
	while(!(inportb(base + PORT_ATAPI_STATUS) & HDS_DRDY));
	
	/* drive ready for the command -- so send it! */
	outportb(base + PORT_ATAPI_COMMAND, ATAPI_READ_WITH_RETRY);
	
	if(sec_count == 0) sec_count = 256;
	
	/* Wait for data to come in */
	while(status & HDS_DRQ) asm("hlt");
	
	temp = kmalloc((sec_count * 512));
	inportw_string(base + PORT_ATAPI_DATA, (sec_count * 256), (unsigned short *)temp);
	swab(temp, data, (sec_count * 512));
	kfree(temp);
	
	if(inportb(base + PORT_ATAPI_STATUS) & HDS_ERR)
		return inportb(base + PORT_ATAPI_ERROR);
	else
		return TRUE;
}

void HdIrqHandler(struct regs *r)
{
	int base;
	
	base = (r->int_no == 0x0E ? 0x1F0 : 0x170);
	
	status = inportb(base + PORT_ATAPI_STATUS);
	dprintf("\nrecieved IRQ; base = %04X, status = %s%s%s%s%s%s%s%s\n", base,\
	(status & HDS_ERR  ? "error " : ""),	(status & HDS_IDX ? "index " : ""),\
	(status & HDS_CORR ? "corr " : ""),	(status & HDS_DRQ ? "data " : ""),\
	(status & HDS_DSC  ? "seek " : ""),	(status & HDS_DF  ? "fault " : ""),\
	(status & HDS_DRDY ? "ready " : ""),	(status & HDS_BSY ? "busy " : ""));
	if(status & HDS_ERR) dprintf("hd: error on port %04X: %02X\n", base, inportb(base + PORT_ATAPI_ERROR));
	
	return;
}
